package com.cskaoyan.config;

import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfiguration {


    @Bean
    public DefaultWebSecurityManager securityManager(AuthorizingRealm realm, DefaultWebSessionManager sessionManager) {
        DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();
        // 如果容器中有注册Authenticator组件，就可以直接注入，设置这个组件
        // 这个组件其实呢不用注册，为什么，Shiro给我们提供了默认的认证器 → ModularRealmAuthenticator
        // 认证器虽然不需要我们来提供，但是认证器中的Realm需要我们来提供 → AuthorizingRealm
        //webSecurityManager.setAuthenticator();
        webSecurityManager.setRealm(realm); // 给默认的Authenticator(Authorizer)提供realm
        webSecurityManager.setSessionManager(sessionManager);
        return webSecurityManager;
    }

    // 登录做完在做Filter
    // ShiroFilter extends OncePerRequestFilter
    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 如果认证失败 shiro会做重定向到/login.jsp
        shiroFilterFactoryBean.setLoginUrl("/wx/auth/unAuth");


        // Map<String,String> 过滤器的链
        // key = uri
        // value = 放行情况
        // 有序的链 → 有序的Map

        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/wx/auth/login", "anon"); // anon → Anonymous 匿名
        filterChainDefinitionMap.put("/wx/auth/unAuth", "anon"); // anon → Anonymous 匿名
        filterChainDefinitionMap.put("/wx/home/index", "anon"); // anon → Anonymous 匿名

        filterChainDefinitionMap.put("/wx/cart/**", "authc"); // authc → 认证
        filterChainDefinitionMap.put("/wx/order/**", "authc"); // authc → 认证
        filterChainDefinitionMap.put("/wx/address/**", "authc"); // authc → 认证

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }
}
